package com.wxy.feiteng.blog02.aspect;

import com.wxy.feiteng.blog02.entity.People;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Component
@Aspect
public class AspectLog02 {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.wxy.feiteng.blog02.controller.*.*(..))")
    public void log(){


    }

    @After("log()")
    public void method(){
        logger.info("---------doBefore------------");
        System.out.println("----------doBefore------------");
    }
    @AfterReturning(returning = "result",pointcut = "log()")
    public void getAfterReturn(Object result){
        System.out.println("--------getAfterReturn("+result+")----------");
    }

    private class RequestLog{
        private String url;
        private String IP;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String IP, String classMethod, Object[] args) {
            this.url = url;
            this.IP = IP;
            this.classMethod = classMethod;
            this.args = args;
        }

        public RequestLog() {
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", IP='" + IP + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
    @Before("log()")
    public  void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request =requestAttributes.getRequest();
        String ip = request.getRemoteAddr();
        String url = request.getRequestURI();
        String  classMethod=  joinPoint.getSignature().getDeclaringTypeName()+"."+ joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
        logger.info("request :{}",requestLog);
        System.out.println(requestLog+"这是拼接的内容");
        System.out.println("执行完毕!");


    }
}


